package org.ucas.faker.web.Config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.ucas.faker.web.utils.wx.WxClient;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableScheduling
public class AuthScheduleConfig implements SchedulingConfigurer {

  @Autowired
  private WxClient client;


  @Override
  public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
    scheduledTaskRegistrar.addTriggerTask(() -> {
      client.authorize();
    }, (TriggerContext triggerContext) -> {
      PeriodicTrigger trigger = new PeriodicTrigger(client.getExpired(), TimeUnit.SECONDS);
      trigger.setFixedRate(true);
      return trigger.nextExecutionTime(triggerContext);
    });
  }
}
